package com.qingcheng.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.aliyun.oss.OSSClient;
import com.qingcheng.exception.ThrowBusinessException;
import com.qingcheng.service.goods.UploadService;
import com.qingcheng.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.util.UUID;

/**
 * @author lin.jia
 */
@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private OSSClient ossClient;

    /**
     * 本地上传
     *
     * @param file     文件对象
     * @param filename 文件名字
     * @param realPath 路径请求
     * @return 路径
     */
    @Override
    public String nativeUpload(byte[] file, String realPath, String filename) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            String filePath = realPath + "/" + filename;
            File desFile = new File(filePath);
            if (!desFile.getParentFile().exists()) {
                desFile.mkdirs();
            }
            fos = new FileOutputStream(desFile);
            bos = new BufferedOutputStream(fos);
            bos.write(file);
        } catch (IOException e) {
            ThrowBusinessException.throwBusinessException("本地上传IO异常");
        }
        try {
            if (ObjectUtil.isNotNulls(fos)) {
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (ObjectUtil.isNotNulls(bos)) {
                bos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "http://localhost:9101/img/" + filename;
    }

    /**
     * 通过oss上传
     *
     * @param file   文件
     * @param folder 文件夹名字
     * @return 路径
     */
    @Override
    public String ossUpload(byte[] file, String filename, String folder) {
        String bucketName = "qingcheng-jialin";
        ByteArrayInputStream inputStream = new ByteArrayInputStream(file);
        String fileName = folder + "/" + UUID.randomUUID() + filename;
        ossClient.putObject(bucketName, fileName, inputStream);
        return "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + fileName;
    }
}